#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_strList << "北京" << "上海" << "天津" << "山东" << "四川" << "重庆" << "广东" << "河南";
    m_model = new QStringListModel(this);
    m_model->setStringList(m_strList);
    ui->listView->setModel(m_model);
    ui->chkEditable->setChecked(true);
    ui->listView->setEditTriggers(QAbstractItemView::EditTrigger::DoubleClicked | QAbstractItemView::EditTrigger::SelectedClicked);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnIniList_clicked()
{
    m_model->setStringList(m_strList);
}

void MainWindow::on_btnListClear_clicked()
{
    m_model->removeRows(0, m_model->rowCount());
}

void MainWindow::on_chkEditable_clicked(bool checked)
{
    if(checked)
        ui->listView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked);
    else
        ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

void MainWindow::on_btnListAppend_clicked()
{
    m_model->insertRow(m_model->rowCount());
    QModelIndex index = m_model->index(m_model->rowCount( ) - 1, 0);
    m_model->setData(index, "new item", Qt::DisplayRole);
    ui->listView->setCurrentIndex(index);
}

void MainWindow::on_btnListInsert_clicked()
{
    QModelIndex index = ui->listView->currentIndex();
    m_model->insertRow(index.row());
    m_model->setData(index, "Insert item", Qt::DisplayRole);
    ui->listView->setCurrentIndex(index);
}

void MainWindow::on_btnListDelete_clicked()
{
    QModelIndex index = ui->listView->currentIndex();
    m_model->removeRow(index.row());
    ui->listView->setCurrentIndex(QModelIndex());
}

void MainWindow::on_btnListSort_clicked()
{
    m_model->sort(0, Qt::DescendingOrder);
    //m_model->sort(0, Qt::AscendingOrder);
}

void MainWindow::on_btnListMoveUp_clicked()
{
    int row = ui->listView->currentIndex().row();
    QModelIndex index = QModelIndex();
    m_model->moveRow(index, row, index, row -1);
}

void MainWindow::on_btnListMoveDown_clicked()
{
    int row = ui->listView->currentIndex().row();
    QModelIndex index = QModelIndex();
    m_model->moveRow(index, row, index, row + 2);
}

void MainWindow::on_btnTextClear_clicked()
{
    ui->plainTextEdit->clear();
}

void MainWindow::on_btnTextImport_clicked()
{
    ui->plainTextEdit->clear();
    QStringList strList = m_model->stringList();
    for(const auto &e : strList)
    {
        ui->plainTextEdit->appendPlainText(e);
    }
}

void MainWindow::on_listView_clicked(const QModelIndex &index)
{
    QString str1 = QString::asprintf("模型索引：row = %d, column = %d", index.row(), index.column());
    QVariant var = m_model->data(index,Qt::DisplayRole);
    QString str2 = var.toString();
    ui->statusbar->showMessage(str1 + str2);
}

